//
//  TrainTargetView.m
//  CoolTennisBall
//
//  Created by Coollang on 16/7/20.
//  Copyright © 2016年 CoolLang. All rights reserved.
//

#import "TrainTargetView.h"
#import "ASValueTrackingSlider.h"
#import "UIImage+ImageFromView.h"
#import "UIImage+Resize.h"
#import "TraintargetSlider.h"
#import <pop/POP.h>
#import "DataModel.h"
#import "RealTimeTrainModel.h"
#import "CustomSlider.h"
#import "NSAttributedString+RichText.h"



#define TotalProgressWidth self.shangxuanSlider.frame.size.width
#define TotalPaisuTarget (140)
#define TotalSwingTarget (300)
#define TotalFaQiuTarget (200)
#define spanfaqiu (5.0)
#define span (10.0)
#define UnitSpace(Total,span) (100/(Total/span))

@interface TrainTargetView ()<ASValueTrackingSliderDataSource>
@property (weak, nonatomic) IBOutlet TraintargetSlider *shangxuanSlider;
@property (weak, nonatomic) IBOutlet TraintargetSlider *pingJiSlider;
@property (weak, nonatomic) IBOutlet TraintargetSlider *xueQiuSlider;
@property (weak, nonatomic) IBOutlet TraintargetSlider *paiSuSlider;

@property (weak, nonatomic) IBOutlet UISegmentedControl *segmentControl;

/** 设置发球训练的目标 */
@property (weak, nonatomic) IBOutlet UILabel *SpeedTargetLabel;
@property (weak, nonatomic) IBOutlet UILabel *maleLevelLabel;
@property (weak, nonatomic) IBOutlet UILabel *famaleLevelLabel;

@property (weak, nonatomic) IBOutlet CustomSlider *faQiumiddleView;

@property (weak, nonatomic) IBOutlet UIView *outBorderView;

/** 上一次设置的目标值 */
@property (nonatomic, strong)RealTimeTrainModel  *lastSetTargetModel;


/** 正手推荐值 */
@property (nonatomic, assign) NSInteger foreHandRecommendHitNum;
@property (nonatomic, assign) NSInteger foreHandRecommendSpeed;
/** 反手推荐值 */
@property (nonatomic, assign) NSInteger backHandRecommendHitNum;
@property (nonatomic, assign) NSInteger backHandRecommendSpeed;
/** 发球推荐值 */
@property (nonatomic, assign)NSInteger faqiuRecommendValue;

/** 获取训练数据--由实时训练控制器传递过来 */
@property (nonatomic, strong) NSMutableArray <RealTimeTrainModel *>*realTimeTrainHistoryData;

@end

@implementation TrainTargetView


- (void)awakeFromNib {
    [super awakeFromNib];
    
    [self configuerSetUpUI];
}

+ (instancetype)trainTargetViewType:(RealTimeTrainType)type {
    TrainTargetView *targetView = nil;
    
    if (type == RealTimeTrainHB) {
        targetView = [[NSBundle mainBundle] loadNibNamed:@"TrainTargetView" owner:nil options:nil].firstObject;
       
    }else if (type == RealTimeTrainFQ){
        targetView = [[NSBundle mainBundle] loadNibNamed:@"FQTrainTargetView" owner:nil options:nil].firstObject;
        
        [targetView.faQiumiddleView setValueChange:^(CGFloat value) {
            
            targetView.lastSetTargetModel.faQiuTargetSpeed = (NSInteger)floor(value * 100 / UnitSpace(targetView.faQiumiddleView.maxValue, targetView.faQiumiddleView.sliderSpan)) *spanfaqiu;
            
            NSString *faqiuString = nil;
            
            if ([NSBundle currentLanguageIsChinese]) {
                faqiuString = [NSString stringWithFormat:@"球速目标  %0.fkm/h",targetView.lastSetTargetModel.faQiuTargetSpeed];
                
                targetView.SpeedTargetLabel.attributedText = [NSAttributedString attributedString:faqiuString subString:@[@"球速目标", @(targetView.lastSetTargetModel.faQiuTargetSpeed).stringValue, @"km/h"] colors:@[kUnSelectedColor, kOrangeColor, kOrangeColor] fonts:@[[UIFont systemFontOfSize:13],SanFranciscoFont(23), SanFranciscoFont(10)]];
            }else {
                faqiuString = [NSString stringWithFormat:@"Ball Speed Target  %0.f km/h",targetView.lastSetTargetModel.faQiuTargetSpeed];
                targetView.SpeedTargetLabel.attributedText = [NSAttributedString attributedString:faqiuString subString:@[@"Ball Speed Target", @(targetView.lastSetTargetModel.faQiuTargetSpeed).stringValue, @"km/h"] colors: @[kUnSelectedColor, kOrangeColor, kOrangeColor] fonts:@[[UIFont systemFontOfSize:13],SanFranciscoFont(23), SanFranciscoFont(10)]];
            }
        }];
    }
    
    return targetView;
    
}



- (void)realTimeTrainHistoryData:(NSMutableArray <RealTimeTrainModel *>*)realTimeTrainHistoryData withTrainType:(RealTimeTrainType)type {
    
    self.realTimeTrainHistoryData = realTimeTrainHistoryData;
    
    if (type == RealTimeTrainHB) {
        [self setForeHandRecommendValue];
        [self setBackHandRecommendValue];
    }else {
        [self setFaQiuRecommendValue];
    }

}

- (IBAction)segmentValueChange:(UISegmentedControl *)sender {
    // 刷新数据
     [self updateRealTimeTrainHBData];
}

// 上旋、平击、削球、拍速
- (IBAction)sliderValueChange:(TraintargetSlider *)sender {
    
    sender.curretTarget = (NSInteger)floor(sender.value * 100 / UnitSpace((sender.maxValue - sender.minValue), sender.sliderSpan)) *sender.sliderSpan + sender.minValue;
    
    if (self.segmentControl.selectedSegmentIndex == 0) {
        // 正手
        switch (sender.tag) {
            case 120:
                self.lastSetTargetModel.frontHandShangXuanTarget = @(sender.curretTarget);
                break;
            case 121:
                self.lastSetTargetModel.frontHandPingJiTarget = @(sender.curretTarget);
                break;
            case 122:
                self.lastSetTargetModel.frontHandXueQiuTarget = @(sender.curretTarget);
                break;
            case 123:
                self.lastSetTargetModel.frontHandPaiSuTargetSpeed = @(sender.curretTarget);
                break;
            default:
                break;
        }
        
    }else if(self.segmentControl.selectedSegmentIndex == 1) {
        // 反手
        switch (sender.tag) {
            case 120:
                self.lastSetTargetModel.backHandShangXuanTarget = @(sender.curretTarget);
                break;
            case 121:
                self.lastSetTargetModel.backHandPingJiTarget = @(sender.curretTarget);
                break;
            case 122:
                self.lastSetTargetModel.backHandXueQiuTarget = @(sender.curretTarget);
                break;
            case 123:
                self.lastSetTargetModel.backHandPaiSuTargetSpeed = @(sender.curretTarget);
                break;
            default:
                break;
        
        }
    }
    
}


- (IBAction)sureButtonClick:(UIButton *)sender {
    
    [self saveRealTimeTrainTargetData];
    
    if (self.selectTargetValue) {
        self.selectTargetValue(self.lastSetTargetModel);
    }
    
}

- (IBAction)recommendButtonClick:(UIButton *)sender {
    if (self.segmentControl != nil && self.foreHandRecommendHitNum >= 20 && self.backHandRecommendHitNum >= 20 && self.foreHandRecommendSpeed >= 20 && self.backHandRecommendSpeed >= 20) {
        
        if (self.segmentControl.selectedSegmentIndex == 0) {
            [self.shangxuanSlider setSliderValueAndCurrentTarget:self.foreHandRecommendHitNum];
            self.lastSetTargetModel.frontHandShangXuanTarget = @(self.foreHandRecommendHitNum);
            
            [self.xueQiuSlider setSliderValueAndCurrentTarget:self.foreHandRecommendHitNum];
            self.lastSetTargetModel.frontHandXueQiuTarget = @(self.foreHandRecommendHitNum);
            
            [self.pingJiSlider setSliderValueAndCurrentTarget:self.foreHandRecommendHitNum];
            self.lastSetTargetModel.frontHandPingJiTarget = @(self.foreHandRecommendHitNum);
            
            [self.paiSuSlider setSliderValueAndCurrentTarget:self.foreHandRecommendSpeed];
            self.lastSetTargetModel.frontHandPaiSuTargetSpeed = @(self.foreHandRecommendSpeed);
        }else {
            [self.shangxuanSlider setSliderValueAndCurrentTarget:self.backHandRecommendHitNum];
            self.lastSetTargetModel.backHandShangXuanTarget = @(self.backHandRecommendHitNum);
            [self.xueQiuSlider setSliderValueAndCurrentTarget:self.backHandRecommendHitNum];
            self.lastSetTargetModel.backHandXueQiuTarget = @(self.backHandRecommendHitNum);
            [self.pingJiSlider setSliderValueAndCurrentTarget:self.backHandRecommendHitNum];
            self.lastSetTargetModel.backHandPingJiTarget = @(self.backHandRecommendHitNum);
            [self.paiSuSlider setSliderValueAndCurrentTarget:self.backHandRecommendSpeed];
            self.lastSetTargetModel.backHandPaiSuTargetSpeed = @(self.backHandRecommendSpeed);
        }
    }
    
    if (self.faQiumiddleView != nil) {
        [self.faQiumiddleView setSliderValueAndCurrentTarget:self.faqiuRecommendValue];
        self.lastSetTargetModel.faQiuTargetSpeed = self.faqiuRecommendValue;
    }
 
}

#pragma mark - 设置推荐值数据
- (void)setFaQiuRecommendValue {
    
    __block CGFloat faqiuAverage = 0;
    [self.realTimeTrainHistoryData enumerateObjectsUsingBlock:^(RealTimeTrainModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        faqiuAverage = [obj averageValue] * 1.25;
        
        if (faqiuAverage > 20) {
            
            *stop = YES;
        }
        
    }];
    
    if (faqiuAverage > 20) {
        
        self.faqiuRecommendValue = ((NSInteger)faqiuAverage - (NSInteger)faqiuAverage % 5);
    }else {
        self.faqiuRecommendValue = 100;
    }
    
}

- (void)setForeHandRecommendValue {

    __block CGFloat foreHandAverageNum = 0;
    
    [self.realTimeTrainHistoryData enumerateObjectsUsingBlock:^(RealTimeTrainModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       
        [obj disposeForeHandData:^(NSDictionary *foreHandData) {
            
            foreHandAverageNum = ([foreHandData[ForeHandHitBallNumber] integerValue] / 2.4);
            foreHandAverageNum = (NSInteger)(foreHandAverageNum - (NSInteger)foreHandAverageNum % 10);
            
        } BackHandData:nil];
        
        if (foreHandAverageNum > 20 && foreHandAverageNum <= 300) {
            *stop = YES;
        }
        
    }];
    
    if (foreHandAverageNum > 20 && foreHandAverageNum <= 300) {
        
        self.foreHandRecommendHitNum = (NSInteger)foreHandAverageNum;
    }else {
        self.foreHandRecommendHitNum = 50;
    }
    
    
    __block CGFloat foreHandAverageSpeed = 0;
    [self.realTimeTrainHistoryData enumerateObjectsUsingBlock:^(RealTimeTrainModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [obj disposeForeHandData:^(NSDictionary *foreHandData) {
            
            foreHandAverageSpeed = ([foreHandData[ForeHandaverageSpeed] integerValue] * 1.25);
            foreHandAverageSpeed = (NSInteger)(foreHandAverageSpeed - (NSInteger)foreHandAverageSpeed % 5);
            
        } BackHandData:nil];
        if (foreHandAverageSpeed > 20 && foreHandAverageSpeed < 140) {
            *stop = YES;
        }
        
    }];
    
    if (foreHandAverageSpeed > 20 && foreHandAverageSpeed < 140) {
        
        self.foreHandRecommendSpeed = (NSInteger)foreHandAverageSpeed;
    }else {
        self.foreHandRecommendSpeed = 50;
    }
  
    
}

- (void)setBackHandRecommendValue {
    
    
    __block NSInteger backHandAverageNum = 0;
    [self.realTimeTrainHistoryData enumerateObjectsUsingBlock:^(RealTimeTrainModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [obj disposeForeHandData:nil BackHandData:^(NSDictionary *backHandData) {
            backHandAverageNum = ([backHandData[BackHandHitBallNumber] integerValue] / 2.4);
            backHandAverageNum = (NSInteger)(backHandAverageNum - (NSInteger)backHandAverageNum % 10);
        }];
        if (backHandAverageNum > 20 && backHandAverageNum <= 300) {
            *stop = YES;
        }
        
    }];
    
    if (backHandAverageNum > 20 && backHandAverageNum <= 300) {
        
        self.backHandRecommendHitNum = (NSInteger)backHandAverageNum;
    }else {
        self.backHandRecommendHitNum = 50;
    }
   
    __block CGFloat backHandAverageSpeed = 0;
    
    [self.realTimeTrainHistoryData enumerateObjectsUsingBlock:^(RealTimeTrainModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [obj disposeForeHandData:nil BackHandData:^(NSDictionary *backHandData) {
            backHandAverageSpeed = ([backHandData[BackHandaverageSpeed] integerValue] * 1.25);
             backHandAverageSpeed =  (NSInteger)(backHandAverageSpeed - (NSInteger)backHandAverageSpeed % 5);
            
        }];
        if (backHandAverageSpeed > 20 && backHandAverageSpeed <= 140) {
            *stop = YES;
        }
        
    }];
    
    if (backHandAverageSpeed > 20 && backHandAverageSpeed < 140) {
        self.backHandRecommendSpeed = (NSInteger)backHandAverageSpeed;
    }else {
        self.backHandRecommendSpeed = 50;
    }
    
}


- (void)addPopAnimation:(UIView *)view beginTime:(double)beginTime isUp:(BOOL)isUp completeBlock:(void(^)())completeBlock {
    POPSpringAnimation *springAnimation = [POPSpringAnimation animationWithPropertyNamed:kPOPViewFrame];
    if (isUp) {
        // NSValue(CGPoint: CGPointMake(button.center.x, button.center.y - kScreenH * 0.5))
        springAnimation.toValue = [NSValue valueWithCGRect:CGRectMake(0, kYFScreenHeight - self.bounds.size.height, kYFScreenWidth, self.bounds.size.height)];
    }else {
        springAnimation.toValue = [NSValue valueWithCGRect:CGRectMake(0, kYFScreenHeight, kYFScreenWidth, self.bounds.size.height)];
    }
    
    // 弹簧的速度
    springAnimation.springSpeed = 10;
    // 弹簧系数
    springAnimation.springBounciness = 8;
    // 设置动画开始的时间
    springAnimation.beginTime = beginTime;
    // 添加到视图 - kPOPViewCenter
    [view pop_addAnimation:springAnimation forKey:nil];
    
    [springAnimation setAnimationDidReachToValueBlock:completeBlock];
    
}

- (void)configuerSetUpUI {
    
    [self.shangxuanSlider setThumbImage:[UIImage imageNamed:@"上旋1"] forState:UIControlStateNormal];
    [self.shangxuanSlider setMinimumTrackTintColor:[UIColor colorWithHex:0xf071a4]];
    
    [self.pingJiSlider setThumbImage:[UIImage imageNamed:@"平击1"] forState:UIControlStateNormal];
    [self.pingJiSlider setMinimumTrackTintColor:[UIColor colorWithHex:0xa38bd6]];
    
    [self.xueQiuSlider setThumbImage:[UIImage imageNamed:@"削球1"] forState:UIControlStateNormal];
    [self.xueQiuSlider setMinimumTrackTintColor:[UIColor colorWithHex:0xf78460]];
    
    [self.paiSuSlider setThumbImage:[UIImage imageNamed:@"拍速1"] forState:UIControlStateNormal];
    [self.paiSuSlider setMinimumTrackTintColor:[UIColor colorWithHex:0xf071a4]];
    
    [self.shangxuanSlider setSliderSpan:span maxValue:TotalSwingTarget minValue:20 dataSource:self];
    
    
    [self.pingJiSlider setSliderSpan:span maxValue:TotalSwingTarget minValue:20 dataSource:self];
    [self.xueQiuSlider setSliderSpan:span maxValue:TotalSwingTarget minValue:20 dataSource:self];
    
    [self.paiSuSlider setSliderSpan:spanfaqiu maxValue:TotalPaisuTarget minValue:20 dataSource:self];
    
    [self.faQiumiddleView setSliderSpan:spanfaqiu maxValue:TotalFaQiuTarget];
    
    self.outBorderView.backgroundColor = [UIColor whiteColor];
    self.outBorderView.layer.borderWidth = 3;
    self.outBorderView.layer.borderColor = [UIColor colorWithHex:0xf2f2f2].CGColor;
    
    
    if ([NSBundle currentLangeuage] == kLanguageChineseSimple) {
        self.maleLevelLabel.attributedText = [NSAttributedString attributedString:@"160-200km/h\n男子职业水准" subString:@[@"160-200", @"km/h", @"男子职业水准"] colors:@[[UIColor whiteColor],[UIColor whiteColor],[UIColor whiteColor]] fonts:@[MYFONT(13),MYFONT(10),MYFONT(12)]];
        
        self.famaleLevelLabel.attributedText = [NSAttributedString attributedString:@"130-170km/h\n女子职业水准" subString:@[@"130-170", @"km/h", @"女子职业水准"] colors:@[[UIColor whiteColor],[UIColor whiteColor],[UIColor whiteColor]] fonts:@[MYFONT(13),MYFONT(10),MYFONT(12)]];
        
    }else if([NSBundle currentLangeuage] == kLanguageFrennch) {
        
        self.maleLevelLabel.attributedText = [NSAttributedString attributedString:@"160-200km/h\nStandards\ndes joueurs" subString:@[@"160-200", @"km/h", @"Standards\ndes joueurs"] colors:@[[UIColor whiteColor],[UIColor whiteColor],[UIColor whiteColor]] fonts:@[MYFONT(13),MYFONT(10),MYFONT(12)]];
        
        self.famaleLevelLabel.attributedText = [NSAttributedString attributedString:@"130-170km/h\nStandards\ndes joueuses" subString:@[@"130-170", @"km/h", @"Standards\ndes joueuses"] colors:@[[UIColor whiteColor],[UIColor whiteColor],[UIColor whiteColor]] fonts:@[MYFONT(13),MYFONT(10),MYFONT(12)]];
        
    }else {
        self.maleLevelLabel.attributedText = [NSAttributedString attributedString:@"160-200km/h\nMen's\nProfessional" subString:@[@"160-200", @"km/h", @"Men's\nProfessional"] colors:@[[UIColor whiteColor],[UIColor whiteColor],[UIColor whiteColor]] fonts:@[MYFONT(13),MYFONT(10),MYFONT(12)]];
        
        self.famaleLevelLabel.attributedText = [NSAttributedString attributedString:@"130-170km/h\nWomen's\nProfessional" subString:@[@"130-170", @"km/h", @"Women's\nProfessional"] colors:@[[UIColor whiteColor],[UIColor whiteColor],[UIColor whiteColor]] fonts:@[MYFONT(13),MYFONT(10),MYFONT(12)]];
    }
    
    
    self.maleLevelLabel.layer.cornerRadius = 6;
    self.famaleLevelLabel.layer.cornerRadius = 6;
    self.maleLevelLabel.clipsToBounds = YES;
    self.famaleLevelLabel.clipsToBounds = YES;
    
    [self updateRealTimeTrainHBData];
    
    [self bringSubviewToFront:self.faQiumiddleView];
}



// 刷新数据
- (void)updateRealTimeTrainHBData {
    
    if (self.segmentControl.selectedSegmentIndex == 0) {
        [self.shangxuanSlider setSliderValueAndCurrentTarget:[self.lastSetTargetModel.frontHandShangXuanTarget integerValue]];
         [self.pingJiSlider setSliderValueAndCurrentTarget:[self.lastSetTargetModel.frontHandPingJiTarget integerValue]];
         [self.xueQiuSlider setSliderValueAndCurrentTarget:[self.lastSetTargetModel.frontHandXueQiuTarget integerValue]];
        
         [self.paiSuSlider setSliderValueAndCurrentTarget:[self.lastSetTargetModel.frontHandPaiSuTargetSpeed integerValue]];
    }else {
        [self.shangxuanSlider setSliderValueAndCurrentTarget:[self.lastSetTargetModel.backHandShangXuanTarget integerValue]];
        
        [self.pingJiSlider setSliderValueAndCurrentTarget:[self.lastSetTargetModel.backHandPingJiTarget integerValue]];
        
        [self.xueQiuSlider setSliderValueAndCurrentTarget:[self.lastSetTargetModel.backHandXueQiuTarget integerValue]];
        [self.paiSuSlider setSliderValueAndCurrentTarget:[self.lastSetTargetModel.backHandPaiSuTargetSpeed integerValue]];
    }
    
    NSString *faqiuString = nil;
    
    if ([NSBundle currentLanguageIsChinese]) {
        faqiuString = [NSString stringWithFormat:@"球速目标  %0.fkm/h",self.lastSetTargetModel.faQiuTargetSpeed];
        
         self.SpeedTargetLabel.attributedText = [NSAttributedString attributedString:faqiuString subString:@[@"球速目标", @(self.lastSetTargetModel.faQiuTargetSpeed).stringValue, @"km/h"] colors:@[kUnSelectedColor, kOrangeColor, kOrangeColor] fonts:@[[UIFont systemFontOfSize:13],SanFranciscoFont(23), SanFranciscoFont(10)]];
    }else {
        
        faqiuString = [NSString stringWithFormat:@"Ball Speed Target  %0.f km/h",self.lastSetTargetModel.faQiuTargetSpeed];
        
        self.SpeedTargetLabel.attributedText = [NSAttributedString attributedString:faqiuString subString:@[@"Ball Speed Target", @(self.lastSetTargetModel.faQiuTargetSpeed).stringValue, @"km/h"] colors: @[kUnSelectedColor, kOrangeColor, kOrangeColor] fonts:@[[UIFont systemFontOfSize:13],SanFranciscoFont(23), SanFranciscoFont(10)]];
    }
    
   [self.faQiumiddleView setSliderValueAndCurrentTarget:self.lastSetTargetModel.faQiuTargetSpeed];
}


- (NSString *)slider:(TraintargetSlider *)slider stringForValue:(float)value {
    return [NSString stringWithFormat:@"%ld",(long)slider.curretTarget];
}

-(void)dealloc {
    NSLog(@"设置目标deallo");
}


- (RealTimeTrainModel *)lastSetTargetModel {
    
    if (_lastSetTargetModel == nil) {
       
        NSString *path = [DataModel writeAndReadRealTimeTargetpathString];
        //1.读取缓存
        _lastSetTargetModel = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        
        
        if (_lastSetTargetModel == nil) {
            // 使用默认值
            _lastSetTargetModel = [[RealTimeTrainModel alloc] init];
        }
        
    }

    return _lastSetTargetModel;
}

// 保存数据
-(void)saveRealTimeTrainTargetData {
    NSString *path = [DataModel writeAndReadRealTimeTargetpathString];
    [NSKeyedArchiver archiveRootObject:self.lastSetTargetModel toFile:path];
}



@end

